package com.example.service.impl;

import com.example.demo.Order;
import com.example.mapper.OrderMapper;
import com.example.remote.InventoryService;
import com.example.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private InventoryService inventoryService;

    @Autowired
    private OrderMapper orderMapper;


    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void placeOrder(String userId, String commodityCode, Integer count) {
        BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
        Order order = new Order().setUserId(userId).setCommodityCode(commodityCode).setCount(count).setMoney(
                orderMoney);
        orderMapper.insertOrder(order);
        boolean deductFlag = inventoryService.deduct(commodityCode, count);
        if(!deductFlag){
            throw new RuntimeException("减库存失败了");
        }
    }

}
